<!--
 * @Description: 使用 https://www.swiper.com.cn/demo/index.html#virtual-slides
 * API: https://www.swiper.com.cn/api/virtual/374.html
 * vue 使用: https://swiperjs.com/vue
 * @Version: 0.0.1
 * @Autor: zhj1214
 * @Date: 2024-02-07 10:07:39
 * @LastEditors: zhj1214
 * @LastEditTime: 2024-09-26 13:48:50
-->
<template>
  <div class="verticalSwipe">
    <!-- 标题 -->
    <div class="verticalSwipe-title items-center">
      <div class="verticalSwipe-title-value">
        {{ $t("lotteryMoney.dqcyrs") }}
        <span style="margin-right: 2px; font-weight: 650">{{ peoples }}</span>
      </div>
    </div>
    <!-- 表头 -->
    <div class="tabelheader items-center">
      <div class="tabelheader-user">{{ $t("lotteryMoney.user") }}</div>
      <div class="tabelheader-team">{{ $t("lotteryMoney.team") }}</div>
      <div class="tabelheader-jyhx">
        {{ $t("lotteryMoney.jyhx") }}
      </div>
      <!-- <div class="tabelheader-hxvalue">{{ $t("lotteryMoney.hxvalue") }}</div> -->
    </div>
    <!-- 轮播 -->
    <template v-if="slides.length > 0">
      <div
        class="item-animation"
        v-for="(item, index) in slides"
        :key="`${item && item.sid}${item && item.id}${item && item.drawTime}`"
      >
        <div
          v-if="index < 5"
          class="item-animation item-bg-flex"
          :class="{
            'item-bg': index % 2 == 0,
          }"
        >
          <div class="item items-center">
            <div class="items-center">
              <ImgNuxt
                class="item-avatar"
                isHttp
                :placeholder="file.avatarDefault"
                :src="item.avatar || file.avatarDefault"
              />
              <div class="item-nickname">{{ item.nickname || "--" }}</div>
            </div>

            <div class="item-team">
              {{ item.teamName }}
            </div>
            <div
              class="item-hax"
              @click.stop="showPopupHash(item.transactionHash)"
            >
              {{ item.transactionHash.substring(0, 2) }}...
              <span class="item-hax-value">{{
                item.transactionHash.substring(
                  item.transactionHash.length - hashScoreLengthCur,
                  item.transactionHash.length
                )
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </template>
    <div v-else class="verticalSwipe-notdata items-center">
      <img
        class="verticalSwipe-notdata-img"
        src="/image/lotterymoney/zwsj-icon.svg"
      />
      <div class="verticalSwipe-notdata-text">
        {{ $t("lotteryMoney.zwsj") }}
      </div>
    </div>
    <!-- 哈希值弹窗 -->
    <HashValuePopup v-model:show="isShowHash" :hashText="hashText" />
  </div>
</template>
<script setup lang="ts" name="verticalSwipe">
import { onMounted } from "vue";
import { getOssFileUrl, navigateI18nTo } from "@/utils";
import { useEventBus, useDateFormat } from "@vueuse/core";
import { getRecentOpenCardRecord } from "@/api/lottery";
import { useLotteryMoneyStore } from "~~/store/modules/lottery-money";
import HashValuePopup from "./hash-value-popup.vue";

const props = withDefaults(
  defineProps<{
    peoples: string | number;
    hashScoreLength: number;
    activitytStatus: number;
  }>(),
  {
    peoples: 0,
    activitytStatus: 1, //   1 未开始  2 进行中  3 已结束
    hashScoreLength: 1,
  }
);

const emit = defineEmits(["lastOpenCard"]);

const lotteryMoneyStore = useLotteryMoneyStore();

const { t } = useI18n();
// 资源
const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
});

// 列表数据
const slides = ref([]);

// socket 消息推送
const openCardSocket = useEventBus("lotteryMoney-socket-bdcLotteryOpenCard"); // 开卡通知
let betSocketOn = openCardSocket.on((val: any) => {
  // 1. pk 位数升级的场景,直接替换2~4名
  if (val.openCardtUser) {
    // 1.1 去重操作,这里保存 20 条id,进行比对

    if (lotteryMoneyStore.$state.openCardIds.length > 0) {
      let isHas = -1;
      const cardId = `${val.openCardtUser.id}${val.openCardtUser.sid}`;
      isHas = lotteryMoneyStore.$state.openCardIds.findIndex(
        (e: any) => e == cardId
      );

      // 重复就不添加了
      if (isHas >= 0) {
        console.log(
          cardId,
          "-1-重复了-1-",
          val.openCardtUser.transactionHash,
          "--",
          isHas
        );
        return;
      }
      // 添加到 ids 中
      lotteryMoneyStore.addOpenCardIds(cardId);
      // lotteryMoneyStore.$patch((state) => {
      //   state.openCardIds = state.openCardIds.unshift(cardId);
      // });
    } else if (lotteryMoneyStore.$state.openCardIds.length == 0) {
      lotteryMoneyStore.addOpenCardIds(
        `${val.openCardtUser.id}${val.openCardtUser.sid}`
      );
    }

    let teamName = "";
    if (val.openCardtUser.teamConfigId == 1) {
      teamName = t("lotteryMoney.redTeam");
    } else if (val.openCardtUser.teamConfigId == 2) {
      teamName = t("lotteryMoney.yellowTeam");
    } else if (val.openCardtUser.teamConfigId == 3) {
      teamName = t("lotteryMoney.blueTeam");
    }

    slides.value.unshift({ ...val.openCardtUser, teamName });
  }
});

/**
 * @description: 获取下注列表: 接口返回的数据,最新的在数组第一条的位置
 * 1. 接口获取的数据,按照最近 5 分钟时间过滤出最近的 50 条,不够则获取最近的 5 条
 * 2. 未开始,计算中,已结束都不展示数据
 */

const getRecentOpenCardRecordRequest = () => {
  if (
    lotteryMoneyStore.$state.activitytStatus == 1 ||
    lotteryMoneyStore.$state.activitytStatus == 6 ||
    lotteryMoneyStore.$state.activitytStatus == 3
  ) {
    slides.value = [];
    return;
  }

  // console.log(
  //   lotteryMoneyStore.isNeedPolling,
  //   "请求getRecentOpenCardRecordRequest:",
  //   useDateFormat(Date.now(), "YYYY-MM-DD HH:mm:ss").value
  // );
  // 是否需要轮询
  if (!lotteryMoneyStore.isNeedPolling) return;

  getRecentOpenCardRecord({ limit: 6 }).then((res) => {
    console.log(
      useDateFormat(Date.now(), "YYYY-MM-DD HH:mm:ss").value,
      "getRecentOpenCardRecordRequest-返回结果:",
      res
    );

    if (res) {
      if (!lotteryMoneyStore.$state.isDoneTop4list) {
        lotteryMoneyStore.$patch((state) => {
          state.isDoneTop4list = state.isUseSocketing && true;
        });
      }

      if (
        res.recentOpenCardRecordList &&
        res.recentOpenCardRecordList.length > 0
      ) {
        let arr = res.recentOpenCardRecordList.map((element: any) => {
          if (element.teamConfigId == 1) {
            element.teamName = t("lotteryMoney.redTeam");
          } else if (element.teamConfigId == 2) {
            element.teamName = t("lotteryMoney.yellowTeam");
          } else if (element.teamConfigId == 3) {
            element.teamName = t("lotteryMoney.blueTeam");
          }
          return element;
        });

        // 回调,告诉父级 最近一次的记录
        emit("lastOpenCard", { a: arr[0], b: arr.length > 1 ? arr[1] : null });
        // 最近的五条记录
        slides.value = arr.slice(0, 5);
        // 保存记录 唯一标识到 ids
        if (lotteryMoneyStore.$state.openCardIds.length == 0) {
          lotteryMoneyStore.$patch((state) => {
            state.openCardIds = slides.value.map((e) => `${e.id}${e.sid}`);
          });
        } else {
          const arr = slides.value.map((e) => `${e.id}${e.sid}`);
          let concats = arr.concat(lotteryMoneyStore.$state.openCardIds);
          concats = [...new Set(concats)]; // 去重
          concats = concats.slice(0, 20);

          lotteryMoneyStore.$patch((state) => {
            state.openCardIds = concats;
          });
        }
      }
    }
  });
};

// 下拉刷新,刷新数据
const refreshTop4 = useEventBus("lottery-money-refresh-top4");
const refreshTop4On = refreshTop4.on(() => {
  getRecentOpenCardRecordRequest();
});
/******************************* 活动状态变更 *******************************/

const activitytStatusWatch = watch(
  () => props.activitytStatus,
  (newVal) => {
    if (newVal != 2 && newVal != 7 && newVal != 8) {
      slides.value = [];
    }
  }
);
/******************************* pk 升级 *******************************/
// 当前是几位 PK
const hashScoreLengthCur = ref(props.hashScoreLength);
const pkNumsWatch = watch(
  () => props.hashScoreLength,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      hashScoreLengthCur.value = newVal;
    }
  }
);

onMounted(() => {
  getRecentOpenCardRecordRequest();
});

onBeforeUnmount(() => {
  betSocketOn && betSocketOn();
  refreshTop4On && refreshTop4On();
  pkNumsWatch && pkNumsWatch();
  activitytStatusWatch && activitytStatusWatch();
});

/**
 * @description: 展示哈希弹窗
 * @param {*} val
 */
const isShowHash = ref(false);
const hashText = ref("");
const showPopupHash = (val: string) => {
  if (val) {
    hashText.value = val;
    isShowHash.value = true;
  }
};
</script>
<style lang="scss" scoped>
.verticalSwipe {
  width: 100%;
  padding-bottom: 10 * 2px;
  min-height: 120 * 2px;
  &-title {
    position: relative;
    justify-content: center;
    &-value {
      padding: 1 * 2px 8 * 2px;
      padding: 4 * 2px 12 * 2px;
      border-top-left-radius: 4 * 2px;
      border-top-right-radius: 4 * 2px;
      font-size: 12 * 2px;
      color: #fff;
      background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
    }
  }
  &-notdata {
    min-height: 120 * 2px;
    flex-direction: column;
    justify-content: center;
    &-text {
      text-align: center;
      font-size: 14 * 2px;
      color: #999da7;
    }
    &-img {
      margin-bottom: 8 * 2px;
      width: 50 * 2px;
    }
  }
  &-record {
    position: absolute;
    top: 0;
    right: 8 * 2px;
    padding: 6.5 * 2px 0;
    color: #2a91ff;
    font-size: 10 * 2px;
    font-weight: 600;
  }
}
.item {
  position: relative;
  justify-content: space-between;
  width: 100%;
  padding: 0 10 * 2px;

  &-bg {
    background: linear-gradient(
      90deg,
      rgba(235, 244, 255, 0) 0%,
      #ebf4ff 50.17%,
      rgba(235, 244, 255, 0) 100%
    );
    &-flex {
      display: flex !important;
      align-items: center;
      // margin: 8 * 2px 0;
      padding: 5.2 * 2px 0;
    }
  }
  &-avatar {
    width: 18 * 2px;
    height: 18 * 2px;
    border-radius: 100px;
    overflow: hidden;
    margin-right: 4 * 2px;
  }

  &-hax {
    white-space: nowrap;
    text-wrap: nowrap;
    white-space: nowrap;
    color: #141924;
    width: 90 * 2px;
    font-size: 12 * 2px;
    text-align: right;
    &-value {
      margin-left: -2 * 2px;
      color: #007bff;
      font-weight: 600;
      font-size: 14 * 2px;
    }
  }
  &-nickname {
    @include multi-line-omit(1);
    min-width: 78 * 2px;
    max-width: 78 * 2px;
    color: #141924;
    font-size: 12 * 2px;
    text-align: left;
  }
  &-team {
    text-align: center;
    width: 45 * 2px;
    color: #141924;
    font-size: 12 * 2px;
  }
}
.item-animation {
  transition: all 0.5s;
}
.list-enter-active,
.list-leave-active {
  transition: all 0.5s;
}

.list-enter, .list-leave-to /* .list-leave-active in <2.1.8 */ {
  opacity: 0;
  transform: translateY(-30px);
}
.tabelheader {
  position: relative;
  justify-content: space-around;
  text-align: center;
  font-size: 11 * 2px;
  font-weight: 590;
  color: #999da7;
  height: 24 * 2px;
  background-color: #f0f3fa;
  &-user {
    position: absolute;
    left: 90px;
    text-align: left;
  }
  &-team {
    position: absolute;
    left: 330px;
    width: 50 * 2px;
    text-align: left;
  }
  &-jyhx {
    position: absolute;
    left: 538px;
    width: 70 * 2px;
    text-align: right;
  }

  &-hxvalue {
    text-align: left;
    width: 102 * 2px;
  }
  &-popover {
    margin-left: -0.5 * 2px;
  }
}
</style>
